<template>
  <div class="form-relation-form" v-if="field.subFormFieldList && field.subFormFieldList.length > 0">
    <el-button class="add-subform-btn" icon="el-icon-plus" @click="handleAdd">
      {{$t('common.base.addModule', {module:''})}}
    </el-button>
    <div class="table-box">
      <el-table
        :data="relationFormData"
        style="width: 100%"
        max-height="500"
        header-row-class-name="common-list-table-header__v2"
        border>
        <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
        <el-table-column 
          v-for="(item, index) in columns" :key="index"
          :prop="item.field"
          :label="item.label"
          :width="item.width" 
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <!-- 地址 -->
            <span v-if="item.formType === 'address'">
              {{ changeTableColumnVal(scope.row, item) }}
            </span>
            <span v-else>
              {{
                $formatFormField(item, scope.row)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.base.operation')"
          >
          <template slot-scope="scope">
            <el-button
              @click="handleDelete(scope.$index, scope.row)"
              type="text"
              size="small">
              {{$t('common.base.delete')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <base-modal :title="title" :show.sync="visible" width="1000px">
      <div class="content">
        <div class="search-box">
          <el-input v-model="keyword" prefix-icon="el-icon-search" :placeholder="$t('common.base.inputKeywordToSearch')" @input="handleSearch"></el-input>
        </div>
        <div class="table-box">
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            max-height="500"
            border
            ref="multipleTable"
            :header-cell-style="{ background:'#FAFAFA', 'font-size': '14px', 'font-weight': '500 !important', color: '#262626 !important' }"
              @select="handleSelectionChange"
              @select-all="handleSelectionChange"
              :row-key="getRowKeys"
            >
            <el-table-column
              type="selection"
              width="55"
              :reserve-selection="true"
            >
            </el-table-column>
            <el-table-column 
              v-for="(item, index) in columns" :key="index"
              :prop="item.field"
              :label="item.label"
              :width="item.width" 
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <!-- 地址 -->
                <span v-if="item.formType === 'address'">
                  {{ changeTableColumnVal(scope.row, item) }}
                </span>
                <span v-else>
                  {{ $formatFormField(item, scope.row) }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagping-box">
          <el-pagination
            class="base-pagination"
            :background="true"
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageInfo.pageSize"
            :current-page="pageInfo.pageNum"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit">{{$t('common.base.save')}}</el-button>
      </div>
    </base-modal>
  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
/* api */
import * as PassApi from '@src/api/PassApi';
import { SUBFORM_FIELDS_ADD_LENGTH_MAX } from '@src/component/form/config';
import _ from 'lodash'
export default {
  name: 'form-relation-form',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    // 编辑工单 || 数据回显
    value(newValue) {
      this.relationFormData = newValue || [];
    },
  },
  components: {},
  data() {
    return {
      relationFormData:this.value || [],
      tableData: [],
      loading:false,
      visible:false,
      multipleSelection:[],
      total:0,
      pageInfo:{
        pageNum: 1,
        pageSize: 10, 
      },
      keyword:''

    }
  },
  computed: {
    // 标题
    title() {
      return this.$t('common.base.addModule', {module: this.field?.displayName || ''});
    },
    // 表单表头
    columns() {
      let columns = []
      if(this.field?.subFormFieldList?.length > 0){
        columns = [...this.field?.subFormFieldList];
        columns.map(field => {
          field.label = field.displayName;
          field.field = field.fieldName;
          if(columns.length > 5 ){
            field.width = 180;
          }
        });
      }
      return columns;
    },
    // 子表单的fieldName
    queryStringFieldName(){
      let subFormFieldList = _.cloneDeep(this.field?.subFormFieldList || [])
      let list = []
      if(subFormFieldList.length > 0){
        const filterKey = [ 'text', 'textarea', 'email', 'phone', 'serialNumber']
        list = subFormFieldList.filter(item => filterKey.includes(item.formType)).map(item => item.fieldName)
      }
      return list
    },
    // 选择的paas应用id
    templateBizId(){
      let cascaderValue = this.field?.setting?.cascaderValue || []
      return cascaderValue[cascaderValue.length - 1] || ''
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    getRowKeys(row) {
      return row.bizId
    },
    handleAdd(){
      if (this.relationFormData.length >= SUBFORM_FIELDS_ADD_LENGTH_MAX) return this.$message.warning(this.$t('common.form.tip.alowAddDataCount', {data1: SUBFORM_FIELDS_ADD_LENGTH_MAX}));
      this.$refs.multipleTable.clearSelection()
      this.visible = true
    },
    onSubmit(){
      let list = []
      this.multipleSelection.forEach(item => {
        let idx = this.relationFormData.findIndex(val => val.bizId == item.bizId)
        if(idx <= -1){
          list.push(item)
        }
      })
      const maxLength = list.length + this.relationFormData.length
      if (maxLength > SUBFORM_FIELDS_ADD_LENGTH_MAX) return this.$message.warning(this.$t('common.form.tip.alowAddDataCount', {data1:SUBFORM_FIELDS_ADD_LENGTH_MAX}));
      this.relationFormData = [ ...this.relationFormData, ...list ]
      this.inputForValue(this.relationFormData);
      this.visible = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async handleDelete(index, row) {
      this.relationFormData.splice(index, 1)
      // 删除的时候也去掉旧的选中的列表数据,且把选中状态也取消
      this.multipleSelection = this.multipleSelection.filter(item => item.bizId !== row.bizId)
      this.$refs.multipleTable.toggleRowSelection(row, false);
    },
    /* 获取添加时弹窗内的列表数据 */
    getDataList() {
      const params = {
        templateBizId: this.templateBizId,
        keyword:this.keyword,
        queryStringFieldName: this.queryStringFieldName,
        ...this.pageInfo
      }

      this.loading = true;
      PassApi.searchList(params)
        .then(res => {
          const { success, data } = res;
          if (!success || !data) return;
          // 处理数据
          data.list = (data?.list || []).map(item => {
            return { ...item.formValue, bizId:item.bizId };
          });
          this.tableData = data.list || [];

          this.total = data.total || 0
        })
        .finally(() => {
          this.loading = false;
        })
        .catch(err => {
          console.error('err', err);
        });
    },

    // 处理表格数据
    changeTableColumnVal(row, item){
      if(item.formType === 'address') return row[item.field]?.all || ''
    },

    // 关键字搜素
    handleSearch: _.debounce(function() {
      this.pageInfo.pageNum = 1;
      this.getDataList()
    }, 500),

    // 切换页数
    handleCurrentChange(val) {
      this.pageInfo.pageNum = val;
      this.getDataList()
    },
  }
}
</script>

<style lang="scss" scoped>
.form-relation-form {
  .add-subform-btn {
    color: $color-primary;
    border-color: $color-primary-light-2;
    background-color: $color-primary-light-1;
    margin-bottom: 12px;
    &:hover {
      background: $color-primary-light-6;
      border-color: $color-primary-light-6;
      color: #fff;
    }
  }
}
.content{
  padding:20px;
  .search-box{
    width: 50%;
    ::v-deep .el-input__inner{
      border: 1px solid #e0e1e2 !important;
    }
    ::v-deep .el-input__inner:focus {
      outline: none;
      border-color: $color-primary-light-6 !important;
    }
  }

  .base-pagination {
    border:none
  }
}
.table-box{
  margin:10px 0;
  ::v-deep .el-table{
    border: 1px solid #ebeef5;
  }
}
</style>